// 引入加密插件
const bcrypt = require('bcryptjs')
const { Op } = require('sequelize')
const dayjs = require('dayjs')
const utc = require('dayjs/plugin/utc')
dayjs.extend(utc)
module.exports = {
	/**
	 * 密码加密助手函数
	 * @param {String} password 原始密码
	 * @return {String} 返回加密后的密码
	 */
	bcryptData(password) {
		// 生成盐
		const salt = bcrypt.genSaltSync(10)
		return bcrypt.hashSync(password, salt)
	},
	/**
	 * 解密助手函数
	 * @param {*} password 未加密的密码
	 * @param {*} user_password 加密的密码
	 * @return Promise 两个密码比对，比对成功返回true 失败返回 false
	 */
	async comparePwd(password, user_password) {
		return await bcrypt.compare(password, user_password)
	},
	/**
	 * 参数验证
	 * @param {*} path 对应rules的路径
	 * @param {*} params 参数对象
	 * @returns
	 */
	async validateResult(path, params) {
		return await this.ctx.validate(path, params)
	},
	/**
	 * 搜素条件拼接
	 * @param {*} params
	 * @returns
	 */
	whereConcat(params) {
		let pageSize = null
		let currentPage = null
		let paramsObj = {}
		let paginationObj = {}
		if (params?.pageSize && params?.currentPage) {
			pageSize = params.pageSize
			currentPage = params.currentPage
		}
		if (pageSize && currentPage) {
			paginationObj['limit'] = toInt(pageSize)
			paginationObj['offset'] = (toInt(currentPage) - 1) * toInt(pageSize)
		}
		if (params && params != null && typeof params == 'object') {
			let obj = params.otherWhere
			for (const key in obj) {
				if (Object.hasOwnProperty.call(obj, key)) {
					const element = obj[key]
					if (element !== '') {
						if (key === 'createdAt') {
							paramsObj[key] = {
								[Op.between]: [
									formDateUtcString(element[0]),
									formDateUtcString(element[1]),
								],
							}
						} else if (key === 'status') {
							paramsObj[key] = {
								[Op.eq]: Boolean(element),
							}
						} else {
							paramsObj[key] = {
								[Op.substring]: element,
							}
						}
					}
				}
			}
		}

		return {
			...paginationObj,
			distinct: true,
			where: { ...paramsObj },
		}
	},
	/**
	 * 转成树形菜单
	 * @param {*} menu
	 */
	transformToTree(menus = []) {
		let res = []
		// 解析数据
		menus.forEach((item) => {
			// 去重
			let IsExisted = res.findIndex((it) => it.id === item.dataValues.id)
			if (IsExisted == -1) {
				res.push(item.dataValues)
			}
		})
		// 排序确保是父级菜单在前
		res.sort((a, b) => {
			return a.parent_pid - b.parent_pid
		})
		let data = []
		let map = {}
		res.forEach((item) => {
			item.children = []
			map[item.id] = item
			// 不是按钮
			if (item.parent_pid === 0) {
				data.push(item)
			} else {
				map[item.parent_pid].children.push(item)
			}
		})

		return data
	},
}
function toInt(str) {
	if (typeof str === 'number') return str
	if (!str) return str
	return parseInt(str, 10) || 0
}
const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
function formDateUtcString(utcString, format = DATE_TIME_FORMAT) {
	return dayjs.utc(utcString).format(format)
}
